package com.hugedata.cdn.util;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

import org.stringtree.json.JSONErrorListener;

//改写StringTree-json
public class CdnJSONValidator {

    public CdnJSONValidator(JSONErrorListener listener) {
        this.listener = listener;
    }

    public CdnJSONValidator() {
        this.listener = null;
    }

    public boolean validate(String input) {

        if (null == input)
            return false;

        input = input.trim();
        if (null != listener) {
            listener.start(input);
        }

        boolean ret = valid(input);
        if (null != listener) {
            listener.end();
        }

        return ret;
    }

    private boolean valid(String input) {
        if ("".equals(input))
            return false;
        boolean ret = true;
        it = new StringCharacterIterator(input);
        c = it.first();
        col = 1;
        if (!value()) {
            ret = error("value", 1);
        } else {
            skipWhiteSpace();
            if (c != '\uFFFF')
                ret = error("end", col);
        }
        return ret;
    }

    private boolean value() {
        return literal("true") || literal("false") || literal("null")
                || string() || number() || object() || array();
    }

    private boolean literal(String text) {
        CharacterIterator ci = new StringCharacterIterator(text);
        char t = ci.first();
        if (c != t)
            return false;
        int start = col;
        boolean ret = true;
        t = ci.next();
        do {
            if (t == '\uFFFF')
                break;
            if (t != nextCharacter()) {
                ret = false;
                break;
            }
            t = ci.next();
        } while (true);
        nextCharacter();
        if (!ret)
            error("literal " + text, start);
        return ret;
    }

    private boolean array() {
        return aggregate('[', ']', false);
    }

    private boolean object() {
        return aggregate('{', '}', true);
    }

    private boolean aggregate(char entryCharacter, char exitCharacter,
            boolean prefix) {
        if (c != entryCharacter)
            return false;
        nextCharacter();
        skipWhiteSpace();
        if (c == exitCharacter) {
            nextCharacter();
            return true;
        }
        do {
            if (prefix) {
                int start = col;
                if (!string())
                    return error("string", start);
                skipWhiteSpace();
                if (c != ':')
                    return error("colon", col);
                nextCharacter();
                skipWhiteSpace();
            }
            if (value()) {
                skipWhiteSpace();
                if (c == ',')
                    nextCharacter();
                else if (c != exitCharacter) {
                    return error("comma or " + exitCharacter, col);
                } else {
                    nextCharacter();
                    return true;
                }
            } else {
                return error("value", col);
            }
            skipWhiteSpace();
        } while (true);
    }

    private boolean number() {
        if (!Character.isDigit(c) && c != '-')
            return false;
        int start = col;
        if (c == '-')
            nextCharacter();
        if (c == '0')
            nextCharacter();
        else if (Character.isDigit(c))
            for (; Character.isDigit(c); nextCharacter())
                ;
        else
            return error("number", start);
        if (c == '.') {
            nextCharacter();
            if (Character.isDigit(c))
                for (; Character.isDigit(c); nextCharacter())
                    ;
            else
                return error("number", start);
        }
        if (c == 'e' || c == 'E') {
            nextCharacter();
            if (c == '+' || c == '-')
                nextCharacter();
            if (Character.isDigit(c))
                for (; Character.isDigit(c); nextCharacter())
                    ;
            else
                return error("number", start);
        }
        return true;
    }

    private boolean string() {
        if (c != '"')
            return false;
        int start = col;
        boolean escaped = false;
        nextCharacter();
        for (; c != '\uFFFF'; nextCharacter()) {
            if (!escaped && c == '\\') {
                escaped = true;
                continue;
            }
            if (escaped) {
                if (!escape())
                    return false;
                escaped = false;
                continue;
            }
            if (c == '"') {
                nextCharacter();
                return true;
            }
        }

        return error("quoted string", start);
    }

    private boolean escape() {
        int start = col - 1;
        if ("\\\"/bfnrtu".indexOf(c) < 0)
            return error(
                    "escape sequence \\\",\\\\,\\/,\\b,\\f,\\n,\\r,\\t or \\uxxxx",
                    start);
        if (c == 'u'
                && (!ishex(nextCharacter()) || !ishex(nextCharacter())
                        || !ishex(nextCharacter()) || !ishex(nextCharacter())))
            return error("unicode escape sequence \\uxxxx", start);
        else
            return true;
    }

    private boolean ishex(char d) {
        return "0123456789abcdefABCDEF".indexOf(c) >= 0;
    }

    private char nextCharacter() {
        c = it.next();
        col++;
        return c;
    }

    private void skipWhiteSpace() {
        for (; Character.isWhitespace(c); nextCharacter())
            ;
    }

    private boolean error(String type, int col) {
        if (listener != null)
            listener.error(type, col);
        return false;
    }

    private JSONErrorListener listener;
    private CharacterIterator it;
    private char              c;
    private int               col;
}

// public class XmfJSONValidator extends JSONValidator {

// public XmfJSONValidator() {
// super(null);
// }

// public boolean validate(String input) {
// input = input.trim();
// // listener.start(input);
// // boolean ret = valid(input);
//
// // 执行父类的valid（）方法�?
// try {
// String methodName = "valid";
// Class paramTypes[] = new Class[1];
// paramTypes[0] = Class.forName("java.lang.String");
// ;
// Object paramValues[] = new Object[1];
// paramValues[0] = input;
// Method method = this.getClass().getMethod(methodName, paramTypes);
// method.setAccessible(true);
// Object res = method.invoke(this, paramValues);
// boolean ret = (Boolean) res;
//
// System.out.println("----" + ret);
// return ret;
// } catch (Exception e) {
//
// e.printStackTrace();
// }
//
// return true;
//
// // listener.end();
//
// }

// public static void main(String[] args) {

// String input = ".";

// new XmfJSONValidator().validate(input);
// }
// }
